﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace VFCons
{
	public partial class BoxSelectMark2 : UserControl
	{
        public EventHandler ButtonClicked;
        public EventHandler<PointF> PictureBox_MouseClick;
        public BoxSelectMark2()
		{
			InitializeComponent();
            buttonBoxSelect.Tag = 0;
            buttonTest.Tag = 1;
            labelMarkFn.Tag = 0;

            VisibleChanged += (s, e) =>
              {
                  if (Visible == false) SelectingFocus = false;
              };

            buttonBoxSelect.Click += (s, e) =>
            {
                _selecting_focus = false;
                if (ButtonClicked != null) ButtonClicked(s, e);

            };
            buttonTest.Click += (s, e) =>
            {
                _selecting_focus = false;
                if (ButtonClicked != null) ButtonClicked(s, e);
            };

			pictureBoxMark.Paint += PictureBoxMark_Paint;
			pictureBoxMark.MouseClick += PictureBoxMark_MouseClick;
			pictureBoxMark.MouseMove += PictureBoxMark_MouseMove;

            buttonSelectFocus.Click += (s, e) =>
              {
                  SelectingFocus = !_selecting_focus;
              };
        }

		public bool  SelectingFocus
		{
            get => _selecting_focus;
            set => _selecting_focus = value;
		}
        private bool _selecting_focus = false;

        PointF GetImageLocation(PointF ptBox, Size sizeBox, Size sizeImg)
        {
            PointF pt = new PointF();
            float sBox = 1.0F * sizeBox.Width / sizeBox.Height;
            float sImg = 1.0F * sizeImg.Width / sizeImg.Height;

            float dw = 0;
            float dh = 0;
            float s = 1.0F;
            if (sBox > sImg)
            {
                s = 1.0F * sizeImg.Height / sizeBox.Height;
                dw = (sizeBox.Width - sizeImg.Width / s) * 0.5F;
                dh = 0;
            }
            else
            {
                s = 1.0F * sizeImg.Width / sizeBox.Width;
                dw = 0;
                dh = (sizeBox.Height - sizeImg.Height / s) * 0.5F;
            }

            pt.X = (ptBox.X - dw) * s;
            pt.Y = (ptBox.Y - dh) * s;
            return pt;
        }

        PointF GetBoxLocation(PointF ptImg, Size sizeBox, Size sizeImg)
        {
            PointF ptBox = new PointF();
            float sBox = 1.0F * sizeBox.Width / sizeBox.Height;
            float sImg = 1.0F * sizeImg.Width / sizeImg.Height;

            float dw = 0;
            float dh = 0;
            float s = 1.0F;
            if (sBox > sImg)
            {
                s = 1.0F * sizeImg.Height / sizeBox.Height;
                dw = (sizeBox.Width - sizeImg.Width / s) * 0.5F;
                dh = 0;
            }
            else
            {
                s = 1.0F * sizeImg.Width / sizeBox.Width;
                dw = 0;
                dh = (sizeBox.Height - sizeImg.Height / s) * 0.5F;
            }

            ptBox.X = ptImg.X / s + dw;
            ptBox.Y = ptImg.Y / s + dh;
            return ptBox;
        }

        private void PictureBoxMark_MouseMove(object sender, MouseEventArgs e)
        {
            if (pictureBoxMark.Image == null) return;
            int iw = pictureBoxMark.Image.Width;
            int ih = pictureBoxMark.Image.Height;
            int pw = pictureBoxMark.Width;
            int ph = pictureBoxMark.Height;

            var pt = GetImageLocation(e.Location, pictureBoxMark.Size, pictureBoxMark.Image.Size);

            if (pt.X < 0 || pt.Y < 0 || pt.X >= iw || pt.Y >= ih)
            {
                return;
            }
            labelGray.Text = pt.X.ToString("F0") + "," + pt.Y.ToString("F0");
        }

        public PointF PointClickedImage
        {
            get
            {
                try
                {
                    var ps = textBoxFocus.Text.Split(new char[] { ',' });
                    _ptInImg.X = Convert.ToSingle(ps[0]);
                    _ptInImg.Y = Convert.ToSingle(ps[1]);
                    return _ptInImg;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, "基准点输入错误" + Environment.NewLine + ex.Message, "ERROR");
                    return new PointF(-1, -1);
                }
            }

            set
            {
                _ptInImg = value;
                textBoxFocus.Text = _ptInImg.X.ToString("F0") + "," + _ptInImg.Y.ToString("F0");
                pictureBoxMark.Invalidate();
            }
        }

        private PointF _ptInImg = new PointF(-1,-1);
        private void PictureBoxMark_MouseClick(object sender, MouseEventArgs e)
		{
            if (pictureBoxMark.Image == null) return;
            if (_selecting_focus == false) return;

            int iw = pictureBoxMark.Image.Width;
            int ih = pictureBoxMark.Image.Height;
            int pw = pictureBoxMark.Width;
            int ph = pictureBoxMark.Height;
            System.Diagnostics.Debug.WriteLine("{0} {1}   {2} {3}", iw, ih, pw, ph);

            var pt = GetImageLocation(e.Location, pictureBoxMark.Size, pictureBoxMark.Image.Size);

            if (pt.X < 0 || pt.Y < 0 || pt.X >= iw || pt.Y >= ih)
            {
                return;
            }
            
            SelectingFocus = false;

            PointClickedImage = pt;
            textBoxFocus.Text = pt.X.ToString("F0") + "," + pt.Y.ToString("F0");

            if (PictureBox_MouseClick != null) PictureBox_MouseClick(sender, PointClickedImage);
            pictureBoxMark.Invalidate();
        }

        public Point PointText = new Point(20, 20);
        private void PictureBoxMark_Paint(object sender, PaintEventArgs e)
		{
            var g = e.Graphics;
            if (pictureBoxMark.Image != null)
            {
                var ptb = GetBoxLocation(_ptInImg, pictureBoxMark.Size, pictureBoxMark.Image.Size);
                g.FillEllipse(Brushes.Orange, ptb.X-5, ptb.Y-5, 10, 10);

                string _text = "FOCUS:" + textBoxFocus.Text;
                g.DrawString(_text, Font, Brushes.Red, PointText);
            }
            System.Diagnostics.Debug.WriteLine("{0}", e.ClipRectangle);
		}

		public static Image From(string fn)
        {
            var fs = new System.IO.FileStream(fn, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            var img = Image.FromStream(fs);
            fs.Close();
            if (img.PixelFormat == PixelFormat.Format8bppIndexed) img.Palette = CreateGrayPalette();
            return img;
        }

        public static ColorPalette CreateGrayPalette()
        {
            ColorPalette palette;
            using (Bitmap bmp = new Bitmap(1, 1, PixelFormat.Format8bppIndexed))
            {
                palette = bmp.Palette;
            }
            for (int i = 0; i < 256; i++)
            {
                palette.Entries[i] = Color.FromArgb(i, i, i);
            }
            return palette;
        }

        public string InitialDir = Application.StartupPath;
        public string DefaultFileName = "default";

        public void SetSelectedMark(Image mark, string mark_label)
        {
            pictureBoxMark.Image = mark;
            labelMarkFn.Text = mark_label;
            labelMarkFn.Tag = 2;
        }

        public void SetMarkFilename(string fn)
        {
            if (string.IsNullOrEmpty(fn))
            {
                labelMarkFn.Text = "NO MARK";
                labelMarkFn.Tag = 0;
                pictureBoxMark.Image = null;
                return;
            }

            if (File.Exists(fn) == false)
            {
                labelMarkFn.Text = "NO MARK FILE";
                labelMarkFn.Tag = 0;
                pictureBoxMark.Image = null;
                MessageBox.Show(this, "MARK文件不存在" + Environment.NewLine + fn, "ERROR");
                return;
            }

            try
            {
                var img = From(fn);
                pictureBoxMark.Image = img;
                labelMarkFn.Text = fn;
                labelMarkFn.Tag = 1;
            }
            catch (Exception ex)
            {
                labelMarkFn.Text = "ERROR:" + fn;
                labelMarkFn.Tag = 0;
                pictureBoxMark.Image = null;
                MessageBox.Show(this, "加载MARK文件失败" + Environment.NewLine + fn + Environment.NewLine + ex.Message, "ERROR");
            }
        }

        public Image Image => pictureBoxMark.Image;

        //public bool TemplateEnable
        //{
        //    get { return checkBoxEnable.Checked; }
        //    set { checkBoxEnable.Checked = value; }
        //}
        public string GetMarkFile()
        {
            int tag = Convert.ToInt32(labelMarkFn.Tag);
            if (tag == 0)//no assign mark
            {
                return "";
            }
            else if (tag == 1)//OK
            {
                return labelMarkFn.Text;
            }
            else if (tag == 2)//selected
            {
                return "NOSAVE";
            }
            return "";
        }

		private void buttonSave_Click(object sender, EventArgs e)
		{
            SaveFileDialog dlg = new SaveFileDialog();
            //dlg.InitialDirectory = GlobalParams.CD.MarkPath;
            dlg.InitialDirectory = InitialDir;
            dlg.Filter = "Image File(*.jpg,*.bmp,*.png)|*.jpg;*.bmp;*.png|All file(*.*)|*.*";
            dlg.DefaultExt = "bmp";
            //dlg.FileName = Path.GetFileNameWithoutExtension(GlobalParams.CD.recipe);
            dlg.FileName = DefaultFileName;
            dlg.AddExtension = true;
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string dst = dlg.FileName;
                pictureBoxMark.Image.Save(dst);
                labelMarkFn.Text = dst;
                labelMarkFn.Tag = 1;
            }
        }

		private void buttonLoad_Click(object sender, EventArgs e)
		{
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.Filter = "Image File(*.jpg,*.bmp,*.png)|*.jpg;*.bmp;*.png|All file(*.*)|*.*";
            //dlg.InitialDirectory = GlobalParams.CD.MarkPath;
            //dlg.FileName = Path.GetFileNameWithoutExtension(GlobalParams.CD.recipe);
            dlg.InitialDirectory = InitialDir;
            dlg.FileName = DefaultFileName;
            dlg.Multiselect = false;
            dlg.CheckPathExists = true;
            dlg.CheckFileExists = true;
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                try
                {
                    string Fn_Mark = dlg.FileName;
                    pictureBoxMark.Image = From(Fn_Mark);
                    labelMarkFn.Text = dlg.FileName;
                    labelMarkFn.Tag = 1;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(this, "ERROR", ex.Message);
                }
            }
        }

		private void buttonClear_Click(object sender, EventArgs e)
		{
            labelMarkFn.Tag = 0;
            labelMarkFn.Text = "";
            textBoxFocus.Text = "-1,-1";
            pictureBoxMark.Image = null;
        }

        public bool FocuseEnabled
        {
            get => textBoxFocus.Enabled;
            set
            {
                if (value == false)
                {
                    textBoxFocus.Text = "-1,-1";
                }
                textBoxFocus.Enabled = value;
                buttonSelectFocus.Enabled = value;
            }
        }
    }
}
